/* Copyright (C) 2012  	Mathieu Marleix <mathieu.marleix@aerian.fr>
 * 						Sébastien Dufay
 * 						Romain Noel
 * 						Nicolas Dennewald
 * 						Slim Aloui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.esiee.mobiliteam;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.esiee.mobiliteam.handler.RSSHandler;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Gere l'affichage des parametres.
 * @author Marleix Mathieu
 * @author Dufay Sébastien
 * @author Romain Noel
 * @author Nicolas Dennewald
 * @author Slim Aloui
 */
public class SettingsActivity extends PreferenceActivity{

	LayoutParams params;
	LinearLayout mainLayout;
	Button but,but2;
	AlertDialog alertDialog;
	private boolean alarmChanged = false, DEBUG = false;
	private SharedPreferences sharedPrefs;
	public Locale locale = null;
	private OnSharedPreferenceChangeListener listener;

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		if (locale != null)
		{
			newConfig.locale = locale;
			Locale.setDefault(locale);
			getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
		}
		setAlarmChanged(false);
		loadSetting();
	}

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);

		addPreferencesFromResource(R.xml.preferences);
		
		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		Configuration config = getBaseContext().getResources().getConfiguration();
		
		listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
			public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
				System.out.println(key+"\n");
				if(key.equals("languages")){
					startActivity(getIntent());
					finish();
				}
				else if(key.equals("alarm_day_delay") || key.equals("perform_day_alarm")){
					if(DEBUG) System.out.println("SettingActivity: Delai changé à " + sharedPrefs.getString("alarm_day_delay", "30") + " AlarmDate " + CalendarActivity.getAlarmdate().toLocaleString() + "\n");
					Date retourDate = CalendarActivity.charger(CalendarActivity.getAlarmdate(), sharedPrefs);
					if(retourDate != null) planifierAlarm();
					setAlarmChanged(true);
					startActivity(getIntent());
					finish();
				}
				else if(key.equals("ressources_ade")){
					String ressources = sharedPrefs.getString("ressources_ade", "");
					String matcheressources = RSSHandler.matchedDate("([0-9,]*[0-9]{1,5})",ressources);
					if(!matcheressources.equals("")){
						Intent intent = getIntent();
						Bundle bundle = new Bundle();
						bundle.putBoolean("erreur", false);
						intent.putExtras(bundle);
						startActivity(intent);
						finish();
					}
				}
			}
		};

		sharedPrefs.registerOnSharedPreferenceChangeListener(listener);
		String lang = sharedPrefs.getString("languages", "");
		if(DEBUG) System.out.println(sharedPrefs.getString("languages", ""));
		if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
		{
			locale = new Locale(lang);
			Locale.setDefault(locale);
			config.locale = locale;
			getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
		}
		loadSetting();
	}
	/**
	 * Chargement de la partie basse de l'ecran de preference 
	 * permettant l'ajout de ressource independamment de la vue
	 * declaree dans settings.xml
	 */
	public void loadSetting(){
		Bundle param = this.getIntent().getExtras();
		Boolean erreur = (Boolean) param.getBoolean("erreur",false);
		
		setContentView(R.layout.setting);

		TextView mTextURL = (TextView) findViewById(R.id.setting_url);
		TextView mTextText = (TextView) findViewById(R.id.setting);
		mTextURL.setMovementMethod(LinkMovementMethod.getInstance());
		StringBuffer text = new StringBuffer();

		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(getString(R.string.help));
		alertDialog.setMessage(getString(R.string.help_text));

		alertDialog.setButton(getString(R.string.ok),new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();

			} }); 

		but = (Button) findViewById(R.id.help_button);
		but.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				alertDialog.show(); 
			}

		});
		
		text.append(getString(R.string.alarm_at) + " " + sharedPrefs.getString("current_alarm_date", getString(R.string.no_alarm))+"\n\n");
		
		if(erreur){
			text.append(getString(R.string.error_url));
		}
		mTextText.setText(text.toString());
		mTextURL.setText(Html.fromHtml("<a href='"+ getString(R.string.url_ADE_config) + "'>"+ getString(R.string.config_url)+"<a/>"));
	}
	/**
	 * Capture the keyboard activity and
	 * override the behavior of the back key. 
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		//Gestion du bouton de retour pour pouvoir relancer l'activity principale.
		switch (keyCode){
			case KeyEvent.KEYCODE_BACK: {
			Intent intent = new Intent(this, TabWidget.class);
			Bundle param = this.getIntent().getExtras();
			Bundle bundle = new Bundle();
			bundle.putString("activityChoice",param.getString("activityChoice"));
			bundle.putBoolean("alarmChanged", isAlarmChanged());
			intent.putExtras(bundle);
			startActivity(intent);
			finish();
			return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	/**
	 * Gestion d'un menu dans la partie setting.
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		// refresh the tabs and their content
		//    	Toast.makeText(RSSFeed.this, "Option", Toast.LENGTH_SHORT).show();
		//Création d'un MenuInflater qui va permettre d'instancier un Menu XML en un objet Menu
		MenuInflater inflater = getMenuInflater();
		//Instanciation du menu XML spécifier en un objet Menu
		inflater.inflate(R.layout.menusetting, menu);
		return true;
	}
	/**
	 * listener du menu
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		//On regarde quel item a été cliqué grâce à son id et on déclenche une action
		switch (item.getItemId()) {
		case R.id.main:
			Intent intent = new Intent(this, TabWidget.class);
			Bundle param = this.getIntent().getExtras();
			Bundle bundle = new Bundle();
			bundle.putString("activityChoice",param.getString("activityChoice"));
			bundle.putBoolean("alarmChanged", isAlarmChanged());
			if(DEBUG) System.out.println("SettingActivity: alarmChanged " + isAlarmChanged() + "\n");
			intent.putExtras(bundle);
			startActivity(intent);
			finish();
			return true;
		case R.id.quitter:
			//Pour fermer l'application il suffit de faire finish()
			super.finish();
			return true;
		}
		return false;
	}

	/**
	 * @return the alarmChanged
	 */
	public boolean isAlarmChanged() {
		return alarmChanged;
	}

	/**
	 * @param alarmChanged the alarmChanged to set
	 */
	public void setAlarmChanged(boolean alarmChanged) {
		this.alarmChanged = alarmChanged;
	}

	/**
	 * Job de planification de l'alarme
	 */
	private void planifierAlarm() {
		//Récupération de l'instance du service AlarmManager.
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

		//On instancie l'Intent qui va étre appelé au moment du alarme.
		Intent intent = new Intent(this, AlarmReceiver.class);
		//On créer le pending Intent qui identifie l'Intent de alarme avec un ID et un/des flag(s)
		PendingIntent pendingintent = PendingIntent.getBroadcast(this, 12345678, intent, 0);

		//On annule l'alarm pour replanifier si besoin
		am.cancel(pendingintent);

		//La on va déclencher un calcul pour connaitre le temps qui nous sépare de la prochaine alarme.
		Calendar alarme  = Calendar.getInstance();
		alarme.set(Calendar.HOUR_OF_DAY, CalendarActivity.getAlarm().getHeure());
		alarme.set(Calendar.MINUTE, CalendarActivity.getAlarm().getMinute());
		alarme.set(Calendar.DAY_OF_MONTH, CalendarActivity.getAlarm().getDay());

		Calendar cal = Calendar.getInstance();
		alarme.set(Calendar.SECOND, 0);
		cal.set(Calendar.SECOND, 0);
		long diff = alarme.getTimeInMillis() - cal.getTimeInMillis();

		//On ajoute le alarme au service de l'AlarmManager
		am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis() + diff, pendingintent);
		if(DEBUG) System.out.println("SettingActivity: Alarme journalière programmée le " + 
				alarme.get(Calendar.DAY_OF_MONTH) + " à " + 
				alarme.get(Calendar.HOUR_OF_DAY) + ":" + + 
				alarme.get(Calendar.MINUTE));
	}
}